import { ref } from 'vue'

export interface CommentItem {
  id: string
  productId: string | number
  author: string
  content: string
  createdAt: number
}

function key(productId: string | number) {
  return `shop_comments_${productId}`
}

export function useComments(productId: string | number) {
  const list = ref<CommentItem[]>(load(productId))

  function load(pid: string | number): CommentItem[] {
    try {
      const raw = localStorage.getItem(key(pid))
      return raw ? JSON.parse(raw) : []
    } catch {
      return []
    }
  }

  function save() {
    localStorage.setItem(key(productId), JSON.stringify(list.value))
  }

  function add(author: string, content: string) {
    const item: CommentItem = {
      id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
      productId,
      author,
      content,
      createdAt: Date.now(),
    }
    list.value.unshift(item)
    save()
  }

  return { list, add }
}

